package com.wwt.blog.imp;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wwt.blog.mapper.SysUserMapper;
import com.wwt.blog.pojo.SysUser;
import com.wwt.blog.service.SysUserService;
import com.wwt.blog.utils.JWTUtils;
import com.wwt.blog.vo.ErrorCode;
import com.wwt.blog.vo.LoginUserVo;
import com.wwt.blog.vo.Result;
import com.wwt.blog.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class SysUserServiceImp implements SysUserService {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    //根据文章ID查询作者
    @Override
    public SysUser getAuthorByAuthorId(Long authorId) {
        SysUser author = sysUserMapper.selectById(authorId);
        if(author == null){
            author=new SysUser();
            author.setNickname("未设置作者名");
        }
        return author;
    }

    //根据Token查找用户
    @Override
    public Result getUserByToken(String token) {
        SysUser user = checkToken(token);
        if (user==null)
           return Result.result_fail(ErrorCode.TOKEN_AUTH_FAILED.getCode(),ErrorCode.TOKEN_AUTH_FAILED.getMsg());
        LoginUserVo userVo = new LoginUserVo();
        BeanUtils.copyProperties(user,userVo);
        userVo.setId(String.valueOf(user.getId()));
        userVo.setId(String.valueOf(user.getId()));
        return Result.result_success(userVo);

    }
//根据账号查找用户
    @Override
    public SysUser getUserByAccount(String account) {
        LambdaQueryWrapper<SysUser> wrapper=new LambdaQueryWrapper();
        wrapper.eq(SysUser::getAccount,account)
                .last("limit 1");
       return sysUserMapper.selectOne(wrapper);
    }

    //插入用户
    @Override
    public void insertUser(SysUser user) {
        sysUserMapper.insert(user);
    }

    //根据ID返回UserVo作者信息  评论功能使用
    @Override
    public UserVo findUserVoByAuthorId(Long id) {
        UserVo userVo = new UserVo();
        SysUser user = sysUserMapper.selectById(id);
        BeanUtils.copyProperties(user,userVo);
        userVo.setId(String.valueOf(user.getId()));
        return userVo;
    }


    //函数 检查Token合法性
    public SysUser checkToken(String token){
        if(StringUtils.isEmpty(token))
            return null;
        System.out.println("#############:"+token);
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        if(stringObjectMap==null)
            return null;
        //检验通过 从redis取出json对象
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if(StringUtils.isEmpty(userJson))
            return null;
        SysUser user = JSON.parseObject(userJson, SysUser.class);
        return user;
    }
}
